package com.leyuangame.core.service.impl;

import com.leyuangame.core.controller.bean.ResponseHandler.LeYuanResult;
import com.leyuangame.core.enums.PlayUserLogType;
import com.leyuangame.core.service.RegisterService;
import com.leyuangame.dao.repository.jpa.PlayUserLogRepository;
import com.leyuangame.dao.repository.jpa.PlayUserRepository;
import com.leyuangame.dao.repository.jpa.user.PlayUser;
import com.leyuangame.dao.repository.jpa.user.PlayUserLog;
import com.leyuangame.utils.MD5;
import com.leyuangame.utils.UKTools;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private PlayUserRepository playUserRepository;

    @Autowired
    private PlayUserLogRepository playUserLogRepository;
    @Transactional
    @Override
    public LeYuanResult registerUser(String phone, String code, String passwd,String inviteUser) {
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(passwd)||StringUtils.isEmpty(code)){
            return LeYuanResult.build(1,"手机号密码验证码不能为空");
        }
        //TODO 验证码验证逻辑
        PlayUser exits = playUserRepository.findPlayUserByMobile(phone);
        if(exits!=null){
            return LeYuanResult.build(1,"手机号已经被注册");
        }
        PlayUser u = new PlayUser();
        u.setLeaderid(inviteUser);//设置邀请上级
        u.setPassword(UKTools.md5(passwd));
        u.setMobile(phone);
        u.setCreatetime(new Date());
        u.setToken(UKTools.getUUID().toLowerCase());
        playUserRepository.save(u);
        //记录日志
        playUserLogRepository.save(new PlayUserLog(u.getId(), PlayUserLogType.用户注册.toString(),phone+"注册成功"));
        return LeYuanResult.ok("注册成功");
    }
}
